package com.guoning.office_system.bean;

import com.guoning.office_system.model.User;
import com.guoning.office_system.utils.TokenProccessor;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


/**
 *
 *
 * @Package: com.guoning.office_system.bean
 * @ClassName: SessionFilter
 * @Description:拦截器
 * @author: ganwh
 * @date: 2019年9月19日 下午2:20:57
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    //标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
    String NO_LOGIN = "登录状态失效，请重新登录";

    //不需要登录就可以访问的路径(比如:注册登录等)
    String[] includeUrls = new String[]{
            "/officeSystem/user/login",
            "/officeSystem/user/register"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HttpSession session = request.getSession();
        String uri = request.getRequestURI();
        String token_client = request.getHeader("Token");
        //是否需要拦截
        boolean needFilter = isNeedFilter(uri);

        if (!needFilter) {
            return true;
        } else {
            // session中包含user对象,则是登录状态
            if(session!=null&&session.getAttribute(token_client) != null){
                User user = (User) session.getAttribute(token_client);
                return true;
            }else{
                Map map = new HashMap();
                map.put("status", 401);
                map.put("message", NO_LOGIN);
                response.setStatus(401);
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json;charset=utf-8");
                JSONObject jsonObject = JSONObject.fromObject(map);
                PrintWriter out = null;
                try {
                    out = response.getWriter();
                    out.print(jsonObject.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    out.flush();
                    out.close();
                }
                return false;
            }
        }
    }

    /**
     * @Author: ganwh
     * @Description: 是否需要过滤
     * @Date: 2020-03-13
     * @param uri
     */
    public boolean isNeedFilter(String uri) {

        for (String includeUrl : includeUrls) {
            if(includeUrl.equals(uri)) {
                return false;
            }
        }

        return true;
    }
}